package com.takepoints.mobile;

import java.io.IOException;

import com.takepoints.android.TPConst;
import com.takepoints.android.services.TPServices;
import com.takepoints.android.vo.ReturnVal;
import com.takepoints.android.util.SecurityUtil;
import com.takepoints.android.util.StringUtil;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ImageView;

@TargetApi(10)
public class VerifyCodeNFC extends BaseActivity {
	
	private static NfcAdapter mAdapter;
	private static PendingIntent mPendingIntent;
	private static IntentFilter[] mFilters;
	private static String[][] mTechLists;
	private int cardId;
	private String pageSrc;
	private String promotionId;
	private String rewardNum;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()   // or .detectAll() for all detectable problems
        .penaltyLog()
        .build());
		
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.verifycodenfc);
        manageMenu(0);
        
        Bundle bundle = this.getIntent().getExtras();
    	cardId = Integer.parseInt(bundle.getString("cardId"));
        pageSrc = bundle.getString("pageSrc");
        if("MyCardRewardDetail".equalsIgnoreCase(pageSrc)){
        	promotionId = bundle.getString("promotionId");
        	rewardNum = bundle.getString("rewardNum");
        	
        } else if("MyCardDetail".equalsIgnoreCase(pageSrc)){
        	ImageView imgNFCLogo = (ImageView)findViewById(R.id.imgNFCLogo);
        	imgNFCLogo.setImageResource(R.drawable.nfc_get_orange);
        	
        } else if("MyOfferDetail".equalsIgnoreCase(pageSrc)){
        	ImageView imgNFCLogo = (ImageView)findViewById(R.id.imgNFCLogo);
        	imgNFCLogo.setImageResource(R.drawable.nfccouponlogo);
        }
    	
    	mAdapter = NfcAdapter.getDefaultAdapter(this);
		mPendingIntent = PendingIntent.getActivity( this, 0
								, new Intent(this , getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
								, 0);
		
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		try{
			ndef.addDataType("*/*");
		} catch(MalformedMimeTypeException e){
			alert("MalformedMimeTypeException : " + e.getMessage());
		}

		mFilters = new IntentFilter[] { ndef, };
		mTechLists = new String[][] {
                new String[] { MifareClassic.class.getName(), NfcA.class.getName() }
		};
	}
	
	private void resolveIntent(Intent intent){
		String action = intent.getAction();
		if(NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
			Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			if(tagFromIntent != null){
				try {
					/*
					Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
					Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
					r.play();
					*/
					String encryptedCode = read(tagFromIntent);
					new VerifyCodeProcess(this).execute(encryptedCode);
					
				} catch(Exception e){
					popup("เกิดความผิดพลาด :\n\n" + e.getMessage());
				}
			}
		}
	}
	
	private String read(Tag tag) throws IOException, FormatException {
		StringBuilder result = new StringBuilder("");
		if(tag != null){
			MifareClassic mfc = MifareClassic.get(tag);
    		if(!mfc.isConnected()) mfc.connect();
    		boolean auth = mfc.authenticateSectorWithKeyA(1, SecurityUtil.getAuthenKey());
    		if(auth){
    			int bCount = mfc.getBlockCountInSector(1);
                int bIndex = 0;
                for(int i=0; i<bCount-1; i++){
                	bIndex = mfc.sectorToBlock(1);
                	if(!mfc.isConnected()) mfc.connect();
                    byte[] data = mfc.readBlock(bIndex + i);
                    
                    result.append(new String(data));
                }
    		} else{
    			popup("เกิดความผิดพลาด :\n\nไม่สามารถทำรายการได้ !");
    		}
    		mfc.close();
		}
		return result.toString();
    }
	
	@Override
	public void onNewIntent(Intent intent){
    	super.onNewIntent(intent);
		resolveIntent(intent);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(mAdapter != null){
			mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
		}
	}

	@Override
	public void onPause(){
		super.onPause();
        if(mAdapter != null){
            mAdapter.disableForegroundDispatch(this);
        }
	}
	
	@Override
	public void onBackPressed(){
		backToDetailPage();
		return;
	}
	
	protected void processTake(Context ctx){
		backToDetailPage();
		return;
	}
	
	private void alertResult(String msg){
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage(msg);
		alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dlgInf, int which){
				backToDetailPage();
			}
		});
		alertbox.show();
	}
	private final void backToDetailPage(){
		Intent detailInt = null;
		if("MyCardDetail".equalsIgnoreCase(pageSrc)){
			detailInt = new Intent(this, MyCardDetail.class);
			
		} else if("MyCardRewardDetail".equalsIgnoreCase(pageSrc)){
			//detailInt = new Intent(this, MyCardRewardDetail.class);
			//detailInt.putExtra("promotionId", promotionId);
			//detailInt.putExtra("rewardNum", rewardNum);
			detailInt = new Intent(this, MyCardDetail.class);
			
		} else if("MyOfferDetail".equalsIgnoreCase(pageSrc)){
			detailInt = new Intent(this, MyOfferDetail.class);
			
		} else if("MyRewardDetail".equalsIgnoreCase(pageSrc)){
			detailInt = new Intent(this, MyRewardDetail.class);
			
		} else{
			detailInt = new Intent(this, Takepoints.class);
		}
		detailInt.putExtra("cardId", String.valueOf(cardId));
		startActivity(detailInt);
		finish();
    }
	
	class VerifyCodeProcess extends AsyncTask<String, Void, ReturnVal>{
		
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		VerifyCodeProcess(Context context){
			this.context = context;
		}
		
		@Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "Taking ...", true);
		}
		
		@Override
        protected ReturnVal doInBackground(String... params){
			String encryptedCode = params[0];
			ReturnVal retVal = null;
			try{
				String nfcId = SecurityUtil.decrypt(encryptedCode, SecurityUtil.KEY_TYPE_PRIVATE);
				
				if("MyCardRewardDetail".equalsIgnoreCase(pageSrc)){
					retVal = TPServices.rewardMyCard( getSharedIntValue(TPConst.PRF_MEMBER_ID)
													, cardId, nfcId, rewardNum);
				} else if("MyCardDetail".equalsIgnoreCase(pageSrc)){
					retVal = TPServices.useMyCard(getSharedIntValue(TPConst.PRF_MEMBER_ID)
						 							, cardId, "NFC", nfcId);
				} else if("MyOfferDetail".equalsIgnoreCase(pageSrc)){
					retVal = TPServices.useMyCoupon(getSharedIntValue(TPConst.PRF_MEMBER_ID)
 													, cardId, "NFC", nfcId);
				} else{
					throw new Exception("ไม่สามารถทำรายการได้ !");
				}
				
			} catch(Exception e){
				alertResult("เกิดความผิดพลาด :\n\n" + e.getMessage());
			}
			return retVal;
		}
		
		@Override
        protected void onPostExecute(ReturnVal retVal){
        	progressDlg.dismiss();
        	if(retVal != null && !StringUtil.isEmpty(retVal.getTrxCode())){
				alertResult( "กรุณาแสดงรหัสนี้แก่พนักงาน : " + retVal.getTrxCode()
						   + "\n\n(" + retVal.getTrxDesc() + ")");
			} else{
				alertResult("เกิดความผิดพลาด :\n\n" + retVal.getMessage());
			}
		}
		
	}
	
}
